package com.xuanzheng.company.servlet;

import com.google.gson.JsonObject;
import com.xuanzheng.company.entity.User;
import com.xuanzheng.company.service.UserService;
import com.xuanzheng.company.service.impl.UserServiceImpl;
import com.xuanzheng.company.util.PasswordUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLEncoder;
import java.util.Map;

/**
 * 处理密码重置请求的Servlet
 */
@WebServlet("/resetPassword")
public class ResetPasswordServlet extends HttpServlet {
    private UserService userService = new UserServiceImpl();

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 设置请求和响应的字符编码
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;charset=UTF-8");
        
        // 获取请求参数
        String name = req.getParameter("name");
        String idCard = req.getParameter("idCard");
        String phone = req.getParameter("phone");
        String phoneBackup = req.getParameter("phoneBackup");
        String newPassword = req.getParameter("newPassword");
        
        // 如果phone为空但phoneBackup不为空，使用phoneBackup的值
        if ((phone == null || phone.trim().isEmpty()) && phoneBackup != null && !phoneBackup.trim().isEmpty()) {
            phone = phoneBackup;
        }

        try {
            // 参数验证
            if (name == null || name.trim().isEmpty()) {
                redirectWithError(resp, "请填写姓名");
                return;
            }
            
            if (idCard == null || idCard.trim().isEmpty()) {
                redirectWithError(resp, "请填写身份证号");
                return;
            }
            
            if (phone == null || phone.trim().isEmpty()) {
                redirectWithError(resp, "请填写手机号");
                return;
            }
            
            if (newPassword == null || newPassword.trim().isEmpty()) {
                redirectWithError(resp, "请填写新密码");
                return;
            }

            // 查询用户
            User user = userService.findUserByNameAndIdCardAndPhone(name, idCard, phone);
            if (user == null) {
                redirectWithError(resp, "未找到匹配的用户信息，请检查姓名、身份证号和手机号是否正确");
                return;
            }

            // 更新密码
            String hashedPassword = PasswordUtil.encryptPassword(newPassword);
            user.setPassword(hashedPassword);
            boolean updated = userService.updateUser(user);

            if (updated) {
                // 密码重置成功，显示成功页面
                showSuccessPage(resp);
            } else {
                redirectWithError(resp, "密码重置失败，请稍后再试");
            }
        } catch (Exception e) {
            e.printStackTrace();
            redirectWithError(resp, "服务器错误，请稍后再试");
        }
    }
    
    /**
     * 显示密码重置成功页面
     */
    private void showSuccessPage(HttpServletResponse resp) throws IOException {
        PrintWriter out = resp.getWriter();
        out.println("<!DOCTYPE html>");
        out.println("<html lang=\"zh-CN\">");
        out.println("<head>");
        out.println("    <meta charset=\"UTF-8\">");
        out.println("    <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">");
        out.println("    <title>轩正公司管理系统 - 密码重置成功</title>");
        out.println("    <link rel=\"stylesheet\" href=\"css/common.css\">");
        out.println("    <link rel=\"stylesheet\" href=\"css/login.css\">");
        out.println("    <link rel=\"stylesheet\" href=\"css/watermark.css\">");
        out.println("    <style>");
        out.println("        .success-container {");
        out.println("            text-align: center;");
        out.println("            padding: 30px;");
        out.println("            background-color: #fff;");
        out.println("            border-radius: 8px;");
        out.println("            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);");
        out.println("            max-width: 500px;");
        out.println("            margin: 50px auto;");
        out.println("        }");
        out.println("        .success-icon {");
        out.println("            font-size: 60px;");
        out.println("            color: #28a745;");
        out.println("            margin-bottom: 20px;");
        out.println("        }");
        out.println("        .countdown {");
        out.println("            font-size: 18px;");
        out.println("            margin-top: 20px;");
        out.println("            color: #6c757d;");
        out.println("        }");
        out.println("    </style>");
        out.println("</head>");
        out.println("<body>");
        out.println("    <div class=\"container\">");
        out.println("        <div class=\"header\">");
        out.println("            <h1>密码重置成功</h1>");
        out.println("        </div>");
        out.println("        <div class=\"success-container\">");
        out.println("            <div class=\"success-icon\">✓</div>");
        out.println("            <h2>密码重置成功！</h2>");
        out.println("            <p>您的密码已经成功重置，请使用新密码登录系统。</p>");
        out.println("            <div class=\"countdown\" id=\"countdown\">3秒后自动跳转到登录页面...</div>");
        out.println("        </div>");
        out.println("    </div>");
        out.println("    <script src=\"js/watermark.js\"></script>");
        out.println("    <script>");
        out.println("        // 倒计时跳转");
        out.println("        let seconds = 3;");
        out.println("        const countdownElement = document.getElementById('countdown');");
        out.println("        const timer = setInterval(function() {");
        out.println("            seconds--;");
        out.println("            countdownElement.textContent = seconds + '秒后自动跳转到登录页面...';");
        out.println("            if (seconds <= 0) {");
        out.println("                clearInterval(timer);");
        out.println("                window.location.href = 'index.html';");
        out.println("            }");
        out.println("        }, 1000);");
        out.println("    </script>");
        out.println("</body>");
        out.println("</html>");
    }
    
    /**
     * 重定向到登录页面并显示错误信息
     */
    private void redirectWithError(HttpServletResponse resp, String errorMessage) throws IOException {
        String encodedMessage = URLEncoder.encode(errorMessage, "UTF-8");
        resp.sendRedirect("forgot_password.html?error=" + encodedMessage);
    }
} 